package com.example.booksystem.controller;


import com.example.booksystem.model.Book;
import com.example.booksystem.service.BookService;
import org.hibernate.engine.jdbc.batch.spi.BatchKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class BookController {
    @Autowired
    private BookService bookService;

       //返回主页
//        @GetMapping("/")
//        public String viewHomePage(Model model){
//            model.addAttribute("listbooks",bookService.getAllBooks());
//            return "index";
//    }


    @GetMapping("/")
    public String viewHomePage(Model model) {
        return findPaginated(1, "bookName", "asc" ,model);
    }


    //添加图书
    @GetMapping("/showNewBookForm")
    public String showBook(Model model){
        Book book = new Book();
        model.addAttribute("book",book);
        return "new_book";
    }

    //保存图书信息
    @PostMapping("/saveBook")
    public String saveBook(@ModelAttribute("book") Book book){
        bookService.saveBook(book);
        return "redirect:/";
    }


    //修改图书信息
    @GetMapping("/showNewBookUpdate{id}")
    public String showFormForUpdate(@PathVariable(value = "id") long id,Model model){
        Book book = bookService.getBookByid(id);

        model.addAttribute("book",book);
        return "update_book";
    }

    //删除图书信息
    @GetMapping("/deleteBook{id}")
    public String deleteStudent(@PathVariable(value = "id") long id){
        this.bookService.deleteBookByid(id);
        return "redirect:/";
    }

    //获取分页数据
    @GetMapping("/page/{pageNo}")
    public String findPaginated(@PathVariable (value = "pageNo") int pageNo,
                                @RequestParam("sortField") String sortField,
                                @RequestParam("sortDir") String sortDir,
                                Model model) {
        int pageSize = 5;

        Page<Book> page = bookService.findPaginated(pageNo, pageSize, sortField, sortDir);

        List<Book> listbook = page.getContent();



        model.addAttribute("currentPage", pageNo);
        model.addAttribute("totalPages", page.getTotalPages());
        model.addAttribute("totalItems", page.getTotalElements());

        model.addAttribute("sortField", sortField);
        model.addAttribute("sortDir", sortDir);
        model.addAttribute("reverseSortDir", sortDir.equals("asc") ? "desc" : "asc");

        model.addAttribute("listbooks", listbook);

        return "index";
    }

    //搜索名字
    @GetMapping("/query{inpname}")
    public String query(@PathVariable(value = "inpname") String inpame,Model model){
        List<Book> listbooks = bookService.findByNameContaining(inpame);
        model.addAttribute("listbooks",listbooks);
        return "index";
    }




    }




